package cn.skycity.common.service.impl;

import cn.hutool.json.JSONUtil;
import cn.skycity.common.service.ISysOauthClientService;
import cn.skycity.common.mapper.SysOauthClientMapper;
import com.skycity.framework.uaa.pojo.dto.RegisteredClientDTO;
import com.skycity.framework.uaa.pojo.entity.SysOauthClient;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Map;

/**
 * @author daiyb2
 * @Title: SysOauthClientServiceImpl
 * @Description:
 * @date 2021/10/30 20:59
 **/
@Service
public class SysOauthClientServiceImpl implements ISysOauthClientService {
    @Resource
    private SysOauthClientMapper sysOauthClientMapper;

    @Override
    public RegisteredClientDTO getById(String id) {
        SysOauthClient sysOauthClient = sysOauthClientMapper.selectById(id);
        return wrap(sysOauthClient);
    }

    @Override
    public RegisteredClientDTO getByClientId(String clientId) {
        SysOauthClient sysOauthClient = sysOauthClientMapper.selectOne(new LambdaQueryWrapper<SysOauthClient>().eq(SysOauthClient::getClientId, clientId));
        return wrap(sysOauthClient);
    }

    public RegisteredClientDTO wrap(SysOauthClient sysOauthClient) {
        RegisteredClientDTO registeredClientDTO = new RegisteredClientDTO();
        registeredClientDTO.setId(sysOauthClient.getId());
        registeredClientDTO.setClientId(sysOauthClient.getClientId());
        registeredClientDTO.setClientSecret(sysOauthClient.getClientSecret());
        registeredClientDTO.setClientName(sysOauthClient.getClientName());
        registeredClientDTO.setClientAuthenticationMethods(new HashSet<>(List.of(sysOauthClient.getClientAuthenticationMethods().split(","))));
        registeredClientDTO.setAuthorizationGrantTypes(new HashSet<>(List.of(sysOauthClient.getAuthorizationGrantTypes().split(","))));
        registeredClientDTO.setScopes(new HashSet<>(List.of(sysOauthClient.getScopes().split(","))));
        registeredClientDTO.setRedirectUris(new HashSet<>(List.of(sysOauthClient.getRedirectUris().split(","))));
        registeredClientDTO.setClientSettings(JSONUtil.toBean(sysOauthClient.getClientSettings(), Map.class));
        registeredClientDTO.setTokenSettings(JSONUtil.toBean(sysOauthClient.getTokenSettings(), Map.class));
        return registeredClientDTO;
    }
}
